package com.sise.thread.buyorder;

/**
 * 作者：idea
 * 日期：2018/6/4
 * 描述：
 */

class ThreadTrain2 implements Runnable{
    private int trainCount=100;
    public Object obj=new Object();

    public boolean flag=true;
    //局部变量不会受到线程安全问题的影响
    @Override
    public void run() {
        if(flag){
            while (trainCount>0) {
                try {
                    Thread.sleep(50);
                } catch (Exception e) {
                }
                //使用了同步代码块，里面用的是this锁
                synchronized (obj) {
                    if (trainCount > 0) {
                        System.out.println(Thread.currentThread().getName() + ":开始售出第" + (100 - trainCount + 1) + "" + "张票");
                    }
                    trainCount--;
                }
            }
        }else{
            while (trainCount>0) {
                try {
                    sale();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    private synchronized void sale() throws InterruptedException {
        //同步代码块 ---走到这个位置的时候，可能会有多个线程进行访问，谁先拿到锁谁就先进行购票
        if (trainCount > 0) {
            Thread.sleep(40);
            System.out.println(Thread.currentThread().getName() + ":开始售出第" + (100 - trainCount + 1) + "" + "张票");
        }
        trainCount--;
    }
}